import { HttpsProxyAgent } from 'https-proxy-agent';
import * as https from 'https';
import { URL } from 'url';
import { ClientRequest } from 'http';

export interface ProxyConfig {
  host: string;
  port: number;
  enabled: boolean;
}

// 默认代理配置
const DEFAULT_PROXY_CONFIG: ProxyConfig = {
  host: '127.0.0.1',
  port: 10809, // HTTP代理端口，已验证工作正常
  enabled: true  // 临时禁用代理来测试
};

// 从环境变量或配置中获取代理设置
export function getProxyConfig(): ProxyConfig {
  return {
    host: process.env.PROXY_HOST || DEFAULT_PROXY_CONFIG.host,
    port: parseInt(process.env.PROXY_PORT || DEFAULT_PROXY_CONFIG.port.toString()),
    enabled: process.env.PROXY_ENABLED !== 'false' && DEFAULT_PROXY_CONFIG.enabled
  };
}

// 创建代理agent
export function createProxyAgent(): HttpsProxyAgent<string> | undefined {
  const config = getProxyConfig();
  
  if (!config.enabled) {
    console.log('🔧 代理已禁用');
    return undefined;
  }
  
  const proxyUrl = `http://${config.host}:${config.port}`;
  console.log(`🌐 使用HTTP代理: ${proxyUrl}`);
  
  try {
    // 使用 6.x 版本的构造方式（如果降级到6.x）
    return new HttpsProxyAgent(proxyUrl);
  } catch (error) {
    console.error('❌ 创建代理agent失败:', error);
    return undefined;
  }
}

// 便捷的HTTPS请求函数
export function httpsRequest(url: string, options: {
  method?: string;
  headers?: Record<string, string>;
  timeout?: number;
  params?: Record<string, string>;
  body?: string;
} = {}): Promise<{
  status: number;
  statusText: string;
  headers: Record<string, string>;
  data: string;
}> {
  return new Promise((resolve, reject) => {
    try {
      const urlObj = new URL(url);
      
      // 添加查询参数
      if (options.params) {
        Object.keys(options.params).forEach(key => {
          urlObj.searchParams.set(key, options.params![key]);
        });
      }
      
      console.log(`🔍 正在请求: ${urlObj.toString()}`);
      console.log(`🔧 使用代理: ${getProxyConfig().enabled ? 'YES' : 'NO'}`);
       
        const requestOptions: https.RequestOptions = {
          hostname: urlObj.hostname,
          port: urlObj.port || 443,
          path: urlObj.pathname + urlObj.search,
          method: options.method || 'GET',
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json',
            'Connection': 'close',
            ...options.headers
          },
          timeout: options.timeout || 30000
        };
      
      // 如果有body数据，设置Content-Length
      if (options.body) {
        const bodyBuffer = Buffer.from(options.body, 'utf8');
        (requestOptions.headers as Record<string, string>)['Content-Length'] = bodyBuffer.length.toString();
      }
      
     // 添加代理agent
      const agent = createProxyAgent();
      if (agent) {
        requestOptions.agent = agent;
      }
      
      const req = https.request(requestOptions, (res) => {
        console.log(`✅ 状态码: ${res.statusCode} ${res.statusMessage}`);
        
        let data = '';
        res.setEncoding('utf8');
        
        res.on('data', (chunk) => {
          data += chunk;
        });
        
        res.on('end', () => {
          try {
            resolve({
              status: res.statusCode || 0,
              statusText: res.statusMessage || '',
              headers: res.headers as Record<string, string>,
              data: data
            });
          } catch (error) {
            reject(new Error(`响应处理错误: ${error}`));
          }
        });
      });
      
      req.on('error', (error) => {
        console.error(`❌ 请求错误: ${error.message}`);
        reject(error);
      });
      
      req.on('timeout', () => {
        req.destroy();
        reject(new Error('请求超时'));
      });
      
      // 如果有body数据，写入请求体
      if (options.body) {
        req.write(options.body);
      }
      
      req.end();
      
    } catch (error) {
      reject(error);
    }
  });
}


// 流式HTTPS请求函数 - 返回ReadableStream
export function httpsRequestStream(url: string, options: {
  method?: string;
  headers?: Record<string, string>;
  timeout?: number;
  params?: Record<string, string>;
  body?: string;
  signal?: AbortSignal; // 新增：支持取消信号
} = {}): ReadableStream<Uint8Array> {
  return new ReadableStream({
    start(controller) {
      let isClosed = false; // 添加状态标记防止重复关闭
      let req: ClientRequest; // 声明req变量用于取消操作
      
      // 安全的controller操作包装函数
      const safeEnqueue = (chunk: Uint8Array) => {
        if (!isClosed) {
          try {
            controller.enqueue(chunk);
          } catch (error) {
            console.error('❌ 安全写入失败:', error);
            isClosed = true;
          }
        }
      };
      
      const safeClose = () => {
        if (!isClosed) {
          try {
            controller.close();
            isClosed = true;
          } catch (error) {
            console.error('❌ 安全关闭失败:', error);
            isClosed = true;
          }
        }
      };
      
      const safeError = (error: Error) => {
        if (!isClosed) {
          try {
            controller.error(error);
            isClosed = true;
          } catch (err) {
            console.error('❌ 安全错误处理失败:', err);
            isClosed = true;
          }
        }
      };
      
      // 监听取消信号
      if (options.signal) {
        options.signal.addEventListener('abort', () => {
          if (req) {
            req.destroy();
          }
          if (!isClosed) {
            safeError(new Error('Request aborted'));
          }
        });
        
        // 如果信号已经被取消，直接返回
        if (options.signal.aborted) {
          safeError(new Error('Request aborted'));
          return;
        }
      }
      
      try {
        const urlObj = new URL(url);
        
        // 添加查询参数
        if (options.params) {
          Object.keys(options.params).forEach(key => {
            urlObj.searchParams.set(key, options.params![key]);
          });
        }
        
 
        
        const requestOptions: https.RequestOptions = {
          hostname: urlObj.hostname,
          port: urlObj.port || 443,
          path: urlObj.pathname + urlObj.search,
          method: options.method || 'GET',
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json',
            'Connection': 'close',
            ...options.headers
          },
          timeout: options.timeout || 30000
        };
      
        // 如果有body数据，设置Content-Length
        if (options.body) {
          const bodyBuffer = Buffer.from(options.body, 'utf8');
          (requestOptions.headers as Record<string, string>)['Content-Length'] = bodyBuffer.length.toString();
        }
      
        // // 添加代理agent
        // const agent = createProxyAgent();
        // if (agent) {
        //   requestOptions.agent = agent;
        // }
      
        req = https.request(requestOptions, (res) => {
          console.log(`✅ 流式响应状态码: ${res.statusCode} ${res.statusMessage}`);
          
          // 检查响应状态
          if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
            safeError(new Error(`HTTP error! status: ${res.statusCode}, statusText: ${res.statusMessage}`));
            return;
          }
          
          // 不设置编码，保持原始Buffer数据
          res.on('data', (chunk: Buffer) => {
            // 使用安全的写入方法
            safeEnqueue(new Uint8Array(chunk));
          });
          
          res.on('end', () => {
            safeClose();
          });
          
          res.on('error', (error) => {
            console.error(`❌ 响应流错误: ${error.message}`);
            safeError(error);
          });
        });
      
        req.on('error', (error) => {
          console.error(`❌ 流式请求错误: ${error.message}`);
          safeError(error);
        });
      
        req.on('timeout', () => {
          req.destroy();
          safeError(new Error('流式请求超时'));
        });
      
        // 如果有body数据，写入请求体
        if (options.body) {
          req.write(options.body);
        }
      
        req.end();
        
      } catch (error) {
        safeError(error instanceof Error ? error : new Error('Unknown error'));
      }
    }
  });
}